package com.zhiyou100.test;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.Properties;
import java.util.Random;
public class Email {
    public static String play() throws Exception {
        String random = random();
        Properties prop = new Properties();
        // 开启debug调试，以便在控制台查看
        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", "smtp.qq.com");
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");

        // 开启SSL加密，否则会失败
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        // 创建session
        Session session = Session.getInstance(prop);
        // 通过session得到transport对象
        Transport ts = session.getTransport();
        // 连接邮件服务器：邮箱类型，帐号，授权码代替密码（更安全）
        ts.connect("smtp.qq.com", "2278014627@qq.com", "wopohzpwwbpudjdh");
        // 创建邮件
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress("2278014627@qq.com"));
        // 指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("2278014627@qq.com"));
        // 邮件的标题
        message.setSubject("JavaMail测试");
        // 邮件的文本内容  可以写html代码
        message.setContent(""
                + "<h1><font color=red>"
                + random
                + "</font></h1>"
                + "", "text/html;charset=UTF-8");
        // 发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            return random;
    }
    public static  String random(){
        Random random = new Random();
        String num="";
        for (int i = 0; i <6 ; i++) {
            num+= String.valueOf(random.nextInt(10));
        }
        return num;
    }

}
